package com.lin.demo.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @Author zimingl
 * @Date 2023/4/2 10:55
 * @Description: TODO
 */

@Component
public class RedisUtil {
    private static RedisTemplate<Object, Object> redisTemplate;

    public void setRedisTemplate(RedisTemplate<Object, Object> redisTemplate) {
        RedisUtil.redisTemplate = redisTemplate;
    }

    /**
     * 使用redis分布式锁
     *
     * @param key key
     * @param value value
     * @param time 过期时间
     * @return true:设置成功
     */
    public static boolean lock(String key, String value, long time) {
        return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(key, value, time, TimeUnit.SECONDS));
    }

    /**
     * 删除分布式锁
     *
     * @param key key
     * @param value value
     * @return true:删除成功
     */
    public static void unlock(String key, String value) {
        // 使用lua脚本实现原子性操作,对比value,防止删除别人的锁
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] " +
                "then " +
                "return redis.call('del',KEYS[1]) " +
                "else " +
                "return 0 " +
                "end ";
        redisTemplate.execute(new DefaultRedisScript<>(script,Long.class), Collections.singletonList(key),value);
    }

    /**
     * 加密
     *
     * @param param param
     * @return String
     */
    public static String handleKey(String param) {
        return DigestUtils.md5Hex(param == null ? "" : param);
    }
}
